package cn.smxy.college.service.impl;

import cn.smxy.client.UserClient;
import cn.smxy.college.mapper.CollegeMapper;
import cn.smxy.college.mapper.CollegePlantMapper;
import cn.smxy.college.service.CollegeService;
import cn.smxy.param.*;
import cn.smxy.pojo.Campus;
import cn.smxy.pojo.College;
import cn.smxy.pojo.CollegePlant;
import cn.smxy.pojo.PlantFamily;
import cn.smxy.util.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CollegeServiceImpl implements CollegeService {

    @Autowired
    private CollegeMapper collegeMapper;
    @Autowired
    private CollegePlantMapper collegePlantMapper;
    @Autowired
    private UserClient userClient;

    /**
     * 添加学校
     *
     * @param college
     * @return
     */
    @Override
    @CacheEvict(value = "list.college", allEntries = true)
    public R save(College college) {
        college.setCreateTime(System.currentTimeMillis());
        college.setModifyTime(System.currentTimeMillis());
        int rows = collegeMapper.insert(college);
        if(rows == 0) {
            log.info("CollegeServiceImpl.save业务结束，结果为:{}","添加失败");
            return R.fail("添加失败");
        }
        log.info("CollegeServiceImpl.save业务结束，结果为:{}","添加成功");
        return R.ok("添加成功");
    }

    /**
     * excel批量导入
     *
     * @param list
     */
    @Override
    public void saveExcel(List<College> list) {

    }

    /**
     * 修改学校信息
     *
     * @param college
     * @return
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(value = "list.college", allEntries = true),
                    @CacheEvict(value = "college", allEntries = true)
            }
    )
    public R update(College college) {
        college.setModifyTime(System.currentTimeMillis());
        int rows = collegeMapper.updateById(college);
        if(rows == 0) {
            log.info("CollegeServiceImpl.update业务结束，结果为:{}","修改失败");
            return R.fail("修改失败");
        }
        log.info("CollegeServiceImpl.update业务结束，结果为:{}","修改成功");
        return R.ok("修改成功");
    }

    /**
     * 删除学校
     * 1.删除对应学校
     * 2.查询校园表中对应的校园认证
     * 3.删除该校所有的学生认证
     * 4.修改对应用户的角色权限
     *
     * @param collegeId
     * @return
     */
    @Override
    @Caching(
            evict = {
                    @CacheEvict(value = "list.college", allEntries = true),
                    @CacheEvict(value = "college", key = "#collegeId")
            }
    )
    public R remove(Long collegeId) {
        // 删除对应学校
        int rows = collegeMapper.deleteById(collegeId);
        if(rows == 0) {
            log.info("CollegeServiceImpl.remove业务结束，结果为:{}","删除学校失败");
            return R.fail("删除失败");
        }
        // 删除成功后，查询校园表中对应的校园认证
        CampusSearchParam campusSearchParam = new CampusSearchParam();
        campusSearchParam.setCollegeId(collegeId);
        campusSearchParam.setPageSize(1000);
        R r1 = userClient.campusPage(campusSearchParam);
        ObjectMapper objectMapper = new ObjectMapper();
        List<Campus> campusList = objectMapper.convertValue(r1.getData(), new TypeReference<List<Campus>>() {
        });
        if(campusList != null && campusList.size() > 0) {
            // 条件封装，删除对应校园认证和修改用户角色权限
            String campusIds = "";
            String userIds = "";
            for (Campus campus : campusList) {
                campusIds += campus.getCampusId() + ",";
                userIds += campus.getUserId() + ",";
            }
            CampusRemoveParam campusRemoveParam = new CampusRemoveParam(campusIds, userIds);
            userClient.campusRemoveBatch(campusRemoveParam);
        }
        QueryWrapper<CollegePlant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("college_id",collegeId);
        collegePlantMapper.delete(queryWrapper);
        log.info("CollegeServiceImpl.remove业务结束，结果为:{}","删除成功");
        return R.ok("删除成功");
    }

    /**
     * excel批量导出
     *
     * @return
     */
    @Override
    public R getAll() {
        return null;
    }

    /**
     * 分页展示所有学校信息
     * 1.条件封装
     * 2.查询并返回
     *
     * @param collegeSearchParam
     * @return
     */
    @Override
//    @Cacheable(value = "list.college", key = "#collegeSearchParam.currentPage+" +
//            "'-'+#collegeSearchParam.pageSize")
    public R page(CollegeSearchParam collegeSearchParam) {
        // 参数拆分
        int currentPage = collegeSearchParam.getCurrentPage();
        int pageSize = collegeSearchParam.getPageSize();
        String collegeName = collegeSearchParam.getCollegeName();
        // 条件封装
        IPage<College> page = new Page<>(currentPage,pageSize);
        QueryWrapper<College> queryWrapper = new QueryWrapper<>();
        if (collegeName != null) {
            queryWrapper.like("college_name",collegeName);
        }
        page = collegeMapper.selectPage(page, queryWrapper);
        long total = page.getTotal();
        List<College> records = page.getRecords();
        R ok = R.ok("查询学校列表成功",records,total);
        log.info("CollegeServiceImpl.page业务结束，结果为:{}",ok);
        return ok;
    }

    /**
     * 查询学校详情(查询学号校验方法)
     * 1.条件封装
     * 2.查询并返回
     *
     * @param collegeDetailParam
     * @return
     */
    @Override
    public R detail(CollegeDetailParam collegeDetailParam) {
        College college = collegeMapper.selectById(collegeDetailParam.getCollegeId());
        if(college == null) {
            log.info("CollegeServiceImpl.detail业务结束，结果为:{}","查询失败，不存在该学校");
            return R.fail("查询失败，不存在该学校");
        }
        log.info("CollegeServiceImpl.detail业务结束，结果为:{}",college);
        return R.ok(college);
    }

    /**
     * 展示所有学校信息
     * 1.查询数据库并返回(get请求，不能直接返回整个实体类)
     *
     * @return
     */
    @Override
//    @Cacheable(value = "list.college",key = "#root.methodName")
    public R list() {
        QueryWrapper<College> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("college_id","college_code","college_name");
        List<College> collegeList = collegeMapper.selectList(queryWrapper);
        R ok = R.ok(collegeList);
        log.info("CollegeServiceImpl.list业务结束，结果为:{}",ok);
        return ok;
    }
}
